package com.ybwh.springboot1.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author chenye
 * @description Base64加密解密类
 * @date 2019/4/18 15:09
 */
@Slf4j
public class Base64Util {

    /**
     * base64解密
     * @param s 待解密字符
     * @return 解密结果
     */
    @SuppressWarnings("restriction")
	public static String getFromBase64(String s) {
        String result = null;
        if (StringUtils.isBlank(s)) {
            return result;
        }
        byte[] b = null;
		BASE64Decoder decoder = new BASE64Decoder();
        try {
            b = decoder.decodeBuffer(s);
            result = new String(b, "utf-8");
        } catch (Exception e) {
            log.error(">>>> getFromBase64() msg={}, s={} <<<<", e.getMessage(), s);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * base64加密
     * @param s 待加密字符
     * @return 加密结果
     */
    @SuppressWarnings("restriction")
	public static String getBase64(String s) {
        String result = null;
        if (StringUtils.isBlank(s)) {
            return result;
        }
        byte[] b = null;
        try {
            b = s.getBytes("utf-8");
        } catch (Exception e) {
            log.error(">>>> getBase64() msg={}, s={} <<<<", e.getMessage(), s);
            e.printStackTrace();
        }
        if (null != b) {
            result = new BASE64Encoder().encode(b);
        }
        return result;
    }

}
